<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="科研项目名称" prop="kyXmName">
        <el-input size="mini"
                  v-model="queryParams.kyXmName"
                  placeholder="请输入科研项目名称"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年度" prop="nd">
        <el-select size="mini" v-model="queryParams.nd" placeholder="请选择年度" clearable>
          <el-option
            v-for="dict in dict.type.year"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="依托工程" prop="ytGc">
        <el-input size="mini"
                  v-model="queryParams.ytGc"
                  placeholder="请输入依托工程"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="甲方单位" prop="jfDw">
        <el-select size="mini" v-model="queryParams.jfDw" placeholder="请选择甲方单位" clearable>
          <el-option
            v-for="dict in dict.type.xmgl_lxwj_pzdw"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="承担单位" prop="cdDw">
        <el-input size="mini"
                  v-model="queryParams.cdDw"
                  placeholder="请输入承担单位"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否开票" prop="sfKp">
        <el-select size="mini" v-model="queryParams.sfKp" placeholder="请选择是否开票" clearable>
          <el-option
            v-for="dict in dict.type.sf"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同状态" prop="htZt">
        <el-select v-model="queryParams.htZt" placeholder="请选择合同状态" size="mini" clearable>
          <el-option
            v-for="dict in dict.type.wtww_htzt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-dropdown trigger="click">
          <el-button type="primary" icon="el-icon-plus">
            新增<i style="color: #d9e5f3;" class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleAdd('委托项目')"><span class="el-icon-plus"></span> 委托项目
            </el-dropdown-item>
            <el-dropdown-item @click.native="handleAdd('委外项目')"><span class="el-icon-plus"></span> 委外项目
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single || !selectedRow || (selectedRow.sdZt !== '未锁')"
          @click="handleUpdate"
          v-hasPermi="['wtww:wtww:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple || !selectedRow || (selectedRow.sdZt !== '未锁')"
          @click="handleDelete"
          v-hasPermi="['wtww:wtww:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wtww:wtww:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['wtww:wtww:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-lock"
          size="mini"
          :disabled="!selectedRow || (selectedRow.sdZt !== '未锁')"
          @click="xmLocking"
          v-hasPermi="['wtww:wtww:locking']"
        >锁定
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-unlock"
          size="mini"
          :disabled="!selectedRow || (selectedRow.sdZt !== '已锁')"
          @click="xmUnlock"
          v-hasPermi="['wtww:wtww:unlock']"
        >解锁
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              v-loading="loading" :data="wtwwList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" width="50"/>
      <el-table-column label="年度" align="center" prop="nd" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.year" :value="scope.row.nd"/>
        </template>
      </el-table-column>
      <el-table-column label="科研项目名称" align="center" prop="kyXmName" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link type="primary">{{ scope.row.kyXmName }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" prop="xmLx" show-overflow-tooltip/>
      <el-table-column label="依托工程" align="center" prop="ytGc" show-overflow-tooltip/>
      <el-table-column label="甲方单位" align="center" prop="jfDw" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.xmgl_lxwj_pzdw" :value="scope.row.jfDw"/>
        </template>
      </el-table-column>
      <el-table-column label="承担单位" align="center" prop="cdDw" show-overflow-tooltip/>
      <el-table-column label="合同金额(元)" align="center" prop="htJe" show-overflow-tooltip/>
      <el-table-column label="是否开票" align="center" prop="sfKp" width="80" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sf" :value="scope.row.sfKp"/>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="ksTime" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ksTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="jsTime" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jsTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center" prop="htZt" show-overflow-tooltip>
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wtww_htzt" :value="scope.row.htZt"/>
        </template>
      </el-table-column>
      <el-table-column label="锁定状态" align="center" prop="sdZt" width="80" show-overflow-tooltip/>
      <el-table-column label="录入人" align="center" prop="createBy" width="80" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wtww:wtww:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wtww:wtww:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改委托委外对话框 -->
    <vxe-modal :title="title" v-model="open" width="70%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="110px">
        <el-tabs type="border-card" v-model="activeName">
          <!-- 基本资料 -->
          <el-tab-pane name="jbzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 基本资料</span>
            <div v-if="activeName === 'jbzl'" style="height: 70vh; overflow-y: auto;">
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">项目信息</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="科研项目名称" prop="kyXmName">
                      <el-input v-model="form.kyXmName" placeholder="请输入科研项目名称"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="年度" prop="nd">
                      <el-select v-model="form.nd" placeholder="请选择年度">
                        <el-option
                          v-for="dict in dict.type.year"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="依托工程" prop="ytGc">
                      <el-input v-model="form.ytGc" placeholder="请输入依托工程"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="甲方单位" prop="jfDw">
                      <el-select v-if="getXmLx === '委外项目'" v-model="form.jfDw" placeholder="请选择甲方单位">
                        <el-option
                          v-for="dict in dict.type.xmgl_lxwj_pzdw"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                      <el-input v-else v-model="form.jfDw" placeholder="请输入甲方单位"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="承担单位" prop="cdDw">
                      <el-select v-if="getXmLx === '委托项目'" v-model="form.cdDw" placeholder="请选择承担单位">
                        <el-option
                          v-for="dict in dict.type.xmgl_lxwj_pzdw"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                      <el-input v-else v-model="form.cdDw" placeholder="请输入承担单位"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同金额(元)" prop="htJe">
                      <el-input type="number" v-model.number="form.htJe" placeholder="请输入合同金额(元)"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="是否开票" prop="sfKp">
                      <el-select v-model="form.sfKp" placeholder="请选择是否开票">
                        <el-option
                          v-for="dict in dict.type.sf"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合同状态" prop="htZt">
                      <el-select v-model="form.htZt" placeholder="请选择合同状态">
                        <el-option
                          v-for="dict in dict.type.wtww_htzt"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="开始时间" prop="ksTime">
                      <el-date-picker clearable style="width: 100%;"
                                      v-model="form.ksTime"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="请选择开始时间">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="结束时间" prop="jsTime">
                      <el-date-picker clearable style="width: 100%;"
                                      v-model="form.jsTime"
                                      type="date"
                                      value-format="yyyy-MM-dd"
                                      placeholder="请选择结束时间">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="成功交付要求" prop="cgJfYq">
                  <el-input :rows="3" v-model="form.cgJfYq" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
              </el-card>

              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">甲方负责人信息</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="甲方姓名" prop="jfFzName">
                      <el-input v-if="getXmLx === '委外项目'" disabled v-model="form.jfFzName" placeholder="请输入甲方姓名" @focus="selectUser">
                        <el-button slot="append" icon="el-icon-search" @click="selectUser" style="color: #1890ff">选择人员
                        </el-button>
                      </el-input>
                      <el-input v-else v-model="form.jfFzName" placeholder="请输入甲方姓名"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="甲方性别" prop="jfFzSex">
                      <el-select v-model="form.jfFzSex" placeholder="请选择甲方性别">
                        <el-option
                          v-for="dict in dict.type.sys_user_sex"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="甲方年龄" prop="jfFzAge">
                      <el-input type="number" v-model="form.jfFzAge" placeholder="请输入甲方年龄"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="甲方专业" prop="jfFzZy">
                      <el-input v-model="form.jfFzZy" placeholder="请输入甲方专业"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="甲方联系电话" prop="jfFzPhone">
                      <el-input v-model="form.jfFzPhone" placeholder="请输入甲方联系电话"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="甲方职称" prop="jfFzZc">
                      <el-input v-model="form.jfFzZc" placeholder="请输入甲方职称"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="甲方联系地址" prop="jfFzLxDz">
                  <el-input v-model="form.jfFzLxDz" placeholder="请输入甲方联系地址"/>
                </el-form-item>
              </el-card>

              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">乙方负责人信息</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="乙方姓名" prop="yfFzName">
                      <el-input v-if="getXmLx === '委托项目'" disabled v-model="form.yfFzName" placeholder="请输入乙方姓名" @focus="selectUser">
                        <el-button slot="append" icon="el-icon-search" @click="selectUser" style="color: #1890ff">选择人员
                        </el-button>
                      </el-input>
                      <el-input v-else v-model="form.yfFzName" placeholder="请输入乙方姓名"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="乙方性别" prop="yfFzSex">
                      <el-select v-model="form.yfFzSex" placeholder="请选择乙方性别">
                        <el-option
                          v-for="dict in dict.type.sys_user_sex"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="乙方年龄" prop="yfFzAge">
                      <el-input type="number" v-model="form.yfFzAge" placeholder="请输入乙方年龄"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="乙方专业" prop="yfFzZy">
                      <el-input v-model="form.yfFzZy" placeholder="请输入乙方专业"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="乙方联系电话" prop="yfFzPhone">
                      <el-input v-model="form.yfFzPhone" placeholder="请输入乙方联系电话"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="乙方职称" prop="yfFzZc">
                      <el-input v-model="form.yfFzZc" placeholder="请输入乙方职称"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="乙方联系地址" prop="yfFzLxDz">
                  <el-input v-model="form.yfFzLxDz" placeholder="请输入乙方联系地址"/>
                </el-form-item>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 款项记录 -->
          <el-tab-pane v-if="this.form.idWhere != null" name="kxjl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 款项记录</span>
            <div v-if="activeName === 'kxjl'" style="height: 70vh; overflow-y: auto;">
              <el-card class="box-card">
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWtwwKxjl">添加</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWtwwKxjl">删除</el-button>
                  </el-col>
                </el-row>
                <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                          :data="wtwwKxjlList" :row-class-name="rowWtwwKxjlIndex" @selection-change="handleWtwwKxjlSelectionChange" ref="wtwwKxjl">
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column label="序号" align="center" prop="index" width="50"/>
                  <el-table-column align="center" label="付款单位" prop="fkDw">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.fkDw" placeholder="请输入付款单位" />
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="付款金额(元)" prop="fkJe">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.fkJe" placeholder="请输入付款金额(元)" />
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="付款时间" prop="fkTime">
                    <template slot-scope="scope">
                      <el-date-picker style="width: 100%;" clearable v-model="scope.row.fkTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择付款时间" />
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 附件资料 -->
          <el-tab-pane v-if="this.form.idWhere != null" name="fjzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 技术资料目录</span>
            <div v-if="activeName === 'fjzl'" style="height: 70vh; overflow-y: auto;">
              <el-card class="box-card">
                <el-row :gutter="20">
                  <el-col :span="4" :xs="24">
                    <div class="head-container">
                      <el-tree
                        :data="fileOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        ref="tree"
                        node-key="id"
                        default-expand-all
                        highlight-current
                        @node-click="handleNodeClick"
                        :render-content="renderContent"
                      />
                    </div>
                  </el-col>
                  <el-col :span="20" :xs="24">
                <el-row :gutter="10" class="mb8">
                  <el-col :span="1.5">
                    <!-- 上传按钮 -->
                    <el-button size="mini" icon="el-icon-upload" type="primary" @click="wtwwFileUpload">上传</el-button>
                  </el-col>
                  <el-col :span="1.5">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWtwwFj">删除
                    </el-button>
                  </el-col>
                </el-row>
                <el-table v-loading="loadingFj" :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                          :data="wtwwFjList" :row-class-name="rowWtwwFjIndex" height="60vh"
                          @selection-change="handleWtwwFjSelectionChange" ref="wtwwFj">
                  <el-table-column type="selection" width="50" align="center"/>
                  <el-table-column label="序号" align="center" prop="index" width="50"/>
                  <el-table-column label="文件类型" align="center" prop="fileType" width="250"/>
                  <el-table-column label="文件名称" align="center" prop="fileName" :formatter="getFileNames"/>
                  <el-table-column label="文件大小" align="center" prop="fileSize" width="150"/>
                  <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleDownload(scope.row)"
                      >下载
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 委托委外导入 -->
    <WtWwDr ref="wtWwDr"/>

    <!-- 执行填报附件上传弹窗 -->
    <vxe-modal title="附件上传" v-model="fjUpload" width="25%" showFooter show-zoom resize @close="fjClose">
      <el-upload
        align="center"
        class="upload-demo"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="20"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :headers="headers"
        ref="fileUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          请上传
          <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button v-if="allFilesUploaded === false" size="mini" type="primary" @click="fjUpload = false">关 闭
        </el-button>
        <el-button v-if="allFilesUploaded === true" size="mini" type="primary" @click="fjClose">上传完成, 关闭
        </el-button>
      </div>

    </vxe-modal>

    <!-- 单选科技人员 -->
    <KjryDx ref="kjrydx"/>

    <!-- 委托委外详情组件 -->
    <WtWwXq ref="wtWwXq"/>
  </div>
</template>

<script>
import {
  addWtww,
  delWtww, delWtwwFj,
  getWtww,
  getWtWwId,
  insertWtwwFjByWtwwId,
  listWtww,
  selectWtwwFjList, selectWtwwKxJlByWtwwId, updateSdztLocking, updateSdztUnlock,
  updateWtww
} from "@/api/xmgl/wtww/wtww";
import WtWwDr from "@/views/xmgl/wtww/wtwwgl/components/WtWwDr";
import {getToken} from "@/utils/auth";
import KjryDx from "@/views/components/kjryXz/kjryDx";
import WtWwXq from "@/views/xmgl/wtww/wtwwgl/components/WtWwXq";

export default {
  name: "Wtww",
  components: {WtWwXq, KjryDx, WtWwDr},
  dicts: ['xmgl_lxwj_pzdw', 'year', 'wtww_htzt', 'sf', 'sys_user_sex'],
  provide() {
    return {
      updateKjRyLabel: (val) => {
        if (this.getXmLx === '委托项目') {
          //赋值给乙方负责人
          this.form.yfFzName = val.name; //姓名
          this.form.yfFzSex = val.sex; //性别
          this.form.yfFzAge = val.age; //年龄
          this.form.yfFzZy = val.sxZy; //专业
          this.form.yfFzPhone = val.phone; //联系电话
        }else {
          //委外项目
          //赋值给甲方负责人
          this.form.jfFzName = val.name; //姓名
          this.form.jfFzSex = val.sex; //性别
          this.form.jfFzAge = val.age; //年龄
          this.form.jfFzZy = val.sxZy; //专业
          this.form.jfFzPhone = val.phone; //联系电话
        }
      },
    };
  },
  data() {
    return {
      wtwwFileType: "合同文档", //默认的附件类型
      defaultProps: {children: "children", label: "label"}, // 表单参数
      fileOptions: [{ //附件类型树表
        id: 1,
        label: '1.合同文档',
        type: '合同文档'
      }, {
        id: 2,
        label: '2.过程文档',
        type: '过程文档'
      }, {
        id: 3,
        label: '3.验收文档',
        type: '验收文档'
      }, {
        id: 4,
        label: '4.其他',
        type: '其他'
      }],
      xg: false, //判断是新增还是修改 (false新增 true修改)
      allFilesUploaded: false, // 添加这个来追踪所有文件是否上传完成
      fjUpload: false, //附件上传弹窗
      //要修改的 委托委外id
      wtwwIdEdit: "",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      fileList: [],
      headers: {Authorization: "Bearer " + getToken()},
      number: 0,
      uploadList: [],
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "docx", "zip"],
      selectedRow: null, // 保存当前选中的行
      getXmLx: null, //用户点击新增后选择的项目类型
      getWtWwId: null, //从后端获取的委托委外主键ID
      activeName: 'jbzl', //初始打开的标签页
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWtwwFj: [],
      // 款项记录子表选中数据
      checkedWtwwKxjl: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 委托委外表格数据
      wtwwList: [],
      // 委托委外附件资料表格数据
      wtwwFjList: [],
      // 款项记录表格数据
      wtwwKxjlList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        xmLx: null,
        sdZt: null,
        kyXmName: null,
        nd: null,
        ytGc: null,
        jfDw: null,
        cdDw: null,
        sfKp: null,
        htZt: null,
        userId: this.$store.state.user.id,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        kyXmName: [{required: true, message: "科研项目名称不能为空", trigger: "blur"}],
        nd: [{required: true, message: "年度不能为空", trigger: "change"}],
        ytGc: [{required: true, message: "依托工程不能为空", trigger: "blur"}],
        jfDw: [{required: true, message: "甲方单位不能为空", trigger: "change"}],
        cdDw: [{required: true, message: "承担单位不能为空", trigger: "blur"}],
        htJe: [{required: true, message: "合同金额(元)不能为空", trigger: "blur"}],
        sfKp: [{required: true, message: "是否开票不能为空", trigger: "change"}],
        ksTime: [{required: true, message: "开始时间不能为空", trigger: "blur"}],
        jsTime: [{required: true, message: "结束时间不能为空", trigger: "blur"}],
        htZt: [{required: true, message: "合同状态不能为空", trigger: "change"}],
        jfFzName: [{required: true, message: "甲方姓名不能为空", trigger: "blur"}],
        jfFzSex: [{required: true, message: "甲方性别不能为空", trigger: "change"}],
        jfFzAge: [{required: true, message: "甲方年龄不能为空", trigger: "blur"}],
        jfFzPhone: [{required: true, message: "甲方联系电话不能为空", trigger: "blur"}],
        yfFzName: [{required: true, message: "乙方姓名不能为空", trigger: "blur"}],
        yfFzSex: [{required: true, message: "乙方性别不能为空", trigger: "change"}],
        yfFzAge: [{required: true, message: "乙方年龄不能为空", trigger: "blur"}],
        yfFzPhone: [{required: true, message: "乙方联系电话不能为空", trigger: "blur"}],
      },
      loadingFj: false,
      // 附件查询参数
      queryParamsFj: {
        pageNum: 1,
        pageSize: 100,
        wtwwId: null,
        fileType: null,
        fileName: null,
        fileSize: null
      },
    };
  },
  created() {
    this.getList();
  },
  watch: {
    activeName(newVal) {
      if (newVal === 'fjzl') {
        this.clickFirstNode();
      }
    }
  },
  mounted() {
    if (this.activeName === 'fjzl') {
      this.clickFirstNode();
    }
  },
  methods: {
    //打开委托委外详情
    handleButtonClick(row) {
      this.$refs.wtWwXq.handleOpen(row);
    },
    // 选择人员相关信息(从人才平台列表获取信息)
    selectUser() {
      this.$refs.kjrydx.handleOpen();
    },
    //锁定
    xmLocking() {
      const row = this.selectedRow; // 获取当前选中的行
      this.$confirm('确定锁定选中记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateSdztLocking(row).then(res => {
          this.getList()
          this.$modal.alertSuccess("锁定成功");
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消锁定'
        });
      });
    },
    //解锁
    xmUnlock() {
      const row = this.selectedRow; // 获取当前选中的行
      this.$confirm('确定解锁选中记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateSdztUnlock(row).then(res => {
          this.getList()
          this.$modal.alertSuccess("解锁成功");
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解锁'
        });
      });
    },
    clickFirstNode() {
      this.$nextTick(() => {
        const firstNode = this.$refs.tree.store.nodesMap['1']; // 默认点击id为1的节点
        if (firstNode) {
          this.$refs.tree.setCurrentKey(firstNode.key);
          this.handleNodeClicks(firstNode.data);
        }
      });
    },
    handleNodeClicks(data) {
      this.loadingFj = true
      this.wtwwFileType = data.type
      this.queryParamsFj.fileType = this.wtwwFileType
      selectWtwwFjList(this.queryParamsFj).then(resFileList => {
        this.wtwwFjList = resFileList.rows;
        this.loadingFj = false
      })
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      this.loadingFj = true
      if (node.level > 0 && node.data.children && node.data.children.length > 0) { // 检查是否有子节点
        const firstChildNode = node.data.children[0]; // 获取第一个子节点
        this.$refs.tree.setCurrentKey(firstChildNode.id); // 设置当前选中的节点为第一个子节点
        data = firstChildNode; // 更新 data 为第一个子节点的数据
        this.wtwwFileType = data.type
        this.queryParamsFj.fileType = this.wtwwFileType
        selectWtwwFjList(this.queryParamsFj).then(resFileList => {
          this.wtwwFjList = resFileList.rows;
          this.loadingFj = false
        })
      } else {
        //根据附件类型查询附件列表
        this.wtwwFileType = data.type
        this.queryParamsFj.fileType = this.wtwwFileType
        selectWtwwFjList(this.queryParamsFj).then(resFileList => {
          this.wtwwFjList = resFileList.rows;
          this.loadingFj = false
        })
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName;
      // 默认方法
      this.$download.resource(resource);
    },
    // 获取文件名原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop(); // 返回文件名部分
    },
    //关闭上传附件弹窗后
    fjClose() {
      this.fileList = []
      this.allFilesUploaded = false
      this.fjUpload = false
    },
    //上传文件之前的钩子
    handleBeforeUpload(file){
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      let that = this;
      if (res.code === 200) {
        this.uploadList.push({name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size)});
        let xzItemFile = {
          "wtwwId": that.getWtWwId,
          "fileName": res.fileName,
          "fileType": that.wtwwFileType,
          "fileSize": that.formatFileSize(file.size)
        };
        let xgItemFile = {
          "wtwwId": that.wtwwIdEdit,
          "fileName": res.fileName,
          "fileType": that.wtwwFileType,
          "fileSize": that.formatFileSize(file.size)
        };
        if (this.xg === false) {
          // 点击新增按钮的上传
          insertWtwwFjByWtwwId(xzItemFile).then(resFil => {
            that.getWtwwFjList();
          })
        } else if (this.xg === true){
          // 点击修改按钮的上传
          insertWtwwFjByWtwwId(xgItemFile).then(resFil => {
            that.getWtwwFjList();
          })
        }
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
      this.allFilesUploaded = true
      this.$modal.msgSuccess("上传成功")
      // this.fjShangChuan = false
    },
    getWtwwFjList() {
      let that = this;
      if (this.xg === false) {
        //点击新增 上传文件后的文件列表
        this.queryParamsFj.wtwwId = this.getWtWwId
        this.queryParamsFj.fileType = this.wtwwFileType
        selectWtwwFjList(this.queryParamsFj).then(resFileList => {
          this.wtwwFjList = resFileList.rows;
        })
      } else {
        //点击修改 上传文件后的文件列表
        this.queryParamsFj.wtwwId = this.wtwwIdEdit
        this.queryParamsFj.fileType = this.wtwwFileType
        selectWtwwFjList(this.queryParamsFj).then(resFileList => {
          this.wtwwFjList = resFileList.rows;
        })
      }
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.fileList = this.fileList.map(item => {
          // 使用replace方法去除name中的特定前缀
          item.name = item.name.split('/').pop();
          return item;
        });
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 附件上传按钮
    wtwwFileUpload() {
      this.fjUpload = true;
    },
    // 点击行后选中该行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 查询委托委外列表 */
    getList() {
      this.loading = true;
      listWtww(this.queryParams).then(response => {
        this.wtwwList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        wtwwId: this.getWtWwId,
        xmLx: this.getXmLx,
        sdZt: null,
        kyXmName: null,
        nd: new Date().getFullYear(),
        ytGc: null,
        jfDw: null,
        cdDw: null,
        htJe: null,
        sfKp: null,
        ksTime: null,
        jsTime: null,
        htZt: null,
        cgJfYq: null,
        jfFzName: null,
        jfFzSex: null,
        jfFzAge: null,
        jfFzZy: null,
        jfFzPhone: null,
        jfFzZc: null,
        jfFzLxDz: null,
        yfFzName: null,
        yfFzSex: null,
        yfFzAge: null,
        yfFzZy: null,
        yfFzPhone: null,
        yfFzZc: null,
        yfFzLxDz: null,
        idWhere: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.wtwwFjList = [];
      this.wtwwKxjlList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let ids = selection.map(item => item.wtwwId)
      if (ids.length === 1) {
        this.ids = ids[0]
      }else {
        this.ids = ids
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(type) {
      this.getXmLx = type
      this.xg = false
      getWtWwId().then(res => {
        this.getWtWwId = res.msg
        this.reset();
      })
      this.activeName = 'jbzl'
      this.open = true;
      this.title = "添加" + type;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getXmLx = row.xmLx || this.selectedRow.xmLx
      // this.reset();
      this.jdsqFileType = "合同文档"
      this.xg = true
      const wtwwId = row.wtwwId || this.ids
      this.wtwwIdEdit = row.wtwwId || this.ids
      getWtww(wtwwId).then(response => {
        this.form = response.data;
        this.wtwwFjList = response.data.wtwwFjList;
        //根据主表ID查询款项记录
        selectWtwwKxJlByWtwwId(wtwwId).then(res => {
          this.wtwwKxjlList = res.data.wtwwKxjlList;
        })
        this.activeName = 'jbzl'
        this.open = true;
        this.title = "修改委托委外";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.wtwwFjList = this.wtwwFjList;
          this.form.wtwwKxjlList = this.wtwwKxjlList;
          if (this.form.idWhere != null) {
            updateWtww(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.xg = false
            });
          } else {
            addWtww(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              // this.open = false;
              this.getList();
              this.handleUpdate(this.form)
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wtwwIds = row.wtwwId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delWtww(wtwwIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 委托委外附件资料序号 */
    rowWtwwFjIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 委托委外附件资料删除按钮操作 */
    handleDeleteWtwwFj() {
      if (this.checkedWtwwFj.length == 0) {
        this.$modal.msgError("请先选择要删除的委托委外附件资料数据");
      } else {
        const fjIds = this.checkedWtwwFj;
        this.$modal.confirm('确定删除选中记录？').then(function() {
          return delWtwwFj(fjIds);
        }).then(() => {
          this.queryParamsFj.wtwwId = this.wtwwIdEdit
          this.queryParamsFj.fileType = this.wtwwFileType
          selectWtwwFjList(this.queryParamsFj).then(resFileList => {
            this.wtwwFjList = resFileList.rows;
          })
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
    /** 复选框选中数据 */
    handleWtwwFjSelectionChange(selection) {
      this.checkedWtwwFj = selection.map(item => item.fjId)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wtww/wtww/export', {
        ...this.queryParams
      }, `wtww_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.$refs.wtWwDr.handleImport();
    },
    /** 款项记录序号 */
    rowWtwwKxjlIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 款项记录添加按钮操作 */
    handleAddWtwwKxjl() {
      let obj = {};
      obj.fkDw = "";
      obj.fkJe = "";
      obj.fkTime = "";
      this.wtwwKxjlList.push(obj);
    },
    /** 款项记录删除按钮操作 */
    handleDeleteWtwwKxjl() {
      if (this.checkedWtwwKxjl.length === 0) {
        this.$modal.msgError("请先选择要删除的款项记录数据");
      } else {
        const wtwwKxjlList = this.wtwwKxjlList;
        const checkedWtwwKxjl = this.checkedWtwwKxjl;
        this.wtwwKxjlList = wtwwKxjlList.filter(function(item) {
          return checkedWtwwKxjl.indexOf(item.index) === -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWtwwKxjlSelectionChange(selection) {
      this.checkedWtwwKxjl = selection.map(item => item.index)
    },
  }
};
</script>
